/**
 * 
 */
package org.pump.client.codec;

import java.sql.SQLException;

import org.apache.mina.core.buffer.IoBuffer;
import org.pump.client.type.NullTerminatedString;
import org.pump.client.type.QueryStatus;
import org.pump.client.type.Varstr;
import org.pump.client.util.MyConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Statement;

/**
 * @author liudong03
 *
 */
public class QueryEvent extends EventData{
	private static final Logger mylog = LoggerFactory
			.getLogger(QueryEvent.class);
	long threadId;
	long execTime;
	short dbLen;
	int errorCode;
	int statusVarsLen;
	QueryStatus queryStatus;
	NullTerminatedString dbname;
	Varstr query;
	
	public boolean getSql(Statement st)
	{
		if(query == null)
		{
			mylog.error("query is null");
			return false;
		}
		
		try {
			mylog.info(Thread.currentThread().getName() + "query sql=" + this.query.getStrContent());
			st.addBatch(this.query.getStrContent());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			mylog.error("can't add batch",e);
			return false;
		}
		return true;
	}
	/**
	 * 
	 */
	public QueryEvent() {
		// TODO Auto-generated constructor stub
	}
	
	public static QueryEvent readBuffer(IoBuffer in,int len)
	{
		if(in.remaining() < len)
		{
			return null;
		}
		
		int sz = 0;
		QueryEvent myevent = new QueryEvent();
		myevent.threadId = in.getUnsignedInt();
		sz += 4;
		myevent.execTime = in.getUnsignedInt();
		sz+= 4;
		myevent.dbLen = in.getUnsigned();
		sz += 1;
		myevent.errorCode = in.getUnsignedShort();
		sz += 2;
		myevent.statusVarsLen = in.getUnsignedShort();
		sz += 2;
		
		myevent.queryStatus = QueryStatus.readBuffer(in, myevent.statusVarsLen);
		if(myevent.queryStatus == null)
		{
			mylog.info("query status null");
			return null;
		}
		sz += myevent.statusVarsLen;
		
		myevent.dbname = NullTerminatedString.readBuffer(in, "US-ASCII");
		sz += myevent.dbname.getSize();
		
		int querysz = len - sz;
		myevent.query = Varstr.readBuffer(in, querysz, "GBK");
		if(myevent.query == null)
		{
			mylog.info("query string null");
			return null;
		}
		return myevent;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "QueryEvent [threadId=" + threadId + ", execTime=" + execTime
				+ ", dbLen=" + dbLen + ", errorCode=" + errorCode
				+ ", statusVarsLen=" + statusVarsLen + ", queryStatus="
				+ queryStatus + ", dbname=" + dbname + ", query=" + query.toString() + "]";
	}

	/**
	 * @return the errorCode
	 */
	public int getErrorCode() {
		return errorCode;
	}

	/**
	 * @return the dbname
	 */
	public NullTerminatedString getDatabaseName() {
		return dbname;
	}

	/**
	 * @return the query
	 */
	public Varstr getQuery() {
		return query;
	}
	
	public String getTableName()
	{
		String result = null;
		int startindex = -1;
		int endindex = -1;
		
		String querysql = this.query.getStrContent();
		int sz = querysql.length();
		
		int beginpos = querysql.indexOf(MyConstant.KEY_WORD);
		if(beginpos < 0)
		{
			mylog.debug("the query don't include table keyword,query=[" + querysql + "]");
			return null;
		}
		
		int startpos = beginpos + MyConstant.KEY_WORD_SIZE;
		
		
		int i = startpos;
		for(; i < sz; i++)
		{
			char ch = querysql.charAt(i);
			if(ch == '`' )
			{
				startindex = i + 1;
				for(i++; i < sz; i++)
				{
					if(querysql.charAt(i) == '`') 
					{
						endindex = i;
						break;
					}
				}
				break;
			}else if(ch != ' ')
			{
				startindex = i;
				for(i++; i < sz; i++)
				{
					char tempchar = querysql.charAt(i);
					if(tempchar == ' ' || tempchar == '(')
					{
						endindex = i;
						break;
					}
				}
				break;
			}
		}
		
		if(startindex == -1 || endindex == -1)
		{
			mylog.error("extract query event tablename fail ,query=[" + querysql + "]" );
			return null;
		}
		result = querysql.substring(startindex,endindex);
		if(result.contains("."))
		{
			String[] array = result.split("\\.");
			if(array.length == 2)
			{
				result = array[1];
			}
		}
		
		return result;
		
	}
	/**
	 * @return the dbname
	 */
	public String getDbname() {
		return dbname.getChardata();
	}
	
	
	
}
